package handle_db;

import java.sql.Statement;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;

public class DB_Connector {
	private Connection connector = null;
	private ResultSet rs = null;
	private Statement stmt = null;
	
	public DB_Connector()
	{
		getConnection();
	}
	
	private void getConnection()
	{
		try{
			Class.forName("org.gjt.mm.mysql.Driver").newInstance();
			
			String url = "jdbc:mysql://127.0.0.1:3306/LANCET_SERVER_DB";
			String username = "lancet";
			String password = "37";
			connector = DriverManager.getConnection(url,username,password);
		}catch(ClassNotFoundException cnfex){
			System.err.println("装载 JDBC／ODBC 驱动程序失败。");
			cnfex.printStackTrace();
		}catch(SQLException sqlex){
			System.err.println("无法连接数据库");
			sqlex.printStackTrace();
		}catch(Exception e){
			System.err.println(e.getMessage());
		}
		
	}
	
	public ResultSet executeQuery(String sql)
	{
		rs = null;
		try{
			stmt = connector.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_READ_ONLY);
			rs = stmt.executeQuery(sql);
		}catch(SQLException ex){
			System.err.println(ex.getMessage());
		}
		return rs;
	}
	
	public int executeUpdate(String sql)
	{
		int result = 0;
		try{
			stmt = connector.createStatement();
			result = stmt.executeUpdate(sql);
		}catch(SQLException ex){
			System.err.println(ex.getMessage());
		}
		
		return result;
	}

	
	
	public void close()
	{
		try{
			if(rs !=null )
				rs.close();
		}catch (Exception e) {
			e.printStackTrace(System.err);
		}
		
		try{
			if(stmt != null)
				stmt.close();
		}catch (Exception e) {
			e.printStackTrace(System.err);
		}
		
		
		
		try{
			if(connector!=null)
				connector.close();
		}catch (Exception e) {
			e.printStackTrace();
		}
		System.out.print("数据库的连接关了");
	}
	
	ResultSet get_rs() {
		return rs;
	}
}


